package com.bajiao.service.cart.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.bajiao.common.constant._Whole;
import com.bajiao.common.exception.DataHandleException;
import com.bajiao.common.system.entity.SysDepartPermission;
import com.bajiao.entity.cart.Cart;
import com.bajiao.entity.discountRule.DiscountRule;
import com.bajiao.entity.discountRule.UserDiscountMark;
import com.bajiao.entity.product.Product;
import com.bajiao.mapper.cart.CartMapper;
import com.bajiao.service.cart.CartService;
import com.bajiao.service.discountRule.DiscountRuleService;
import com.bajiao.service.discountRule.UserDiscountMarkService;
import com.bajiao.service.product.ProductService;
import com.bajiao.vo.cart.CartResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 购物车表
 * @Author: FanJq
 * @Date:   2025-01-13
 * @Version: V1.0
 */
@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService {

    @Resource
    private ProductService productService;
    @Resource
    private DiscountRuleService discountRuleService;
    @Resource
    private UserDiscountMarkService discountMarkService;

    /**
     * @Description
     * 添加购物车
     * @date 2025/1/13 10:57
     * @author FanJq
     * @param userId
     * @param productId
     * @param buyNum
     * @return
    */
    @Override
    public Cart create(String userId, String productId, Integer buyNum) {
        Product product = productService.getById(productId);
        if (ObjectUtil.isNull(product) || product.getDelFlag() == _Whole.ONE || product.getStatus() == _Whole.ZERO)
            throw new DataHandleException("商品已下架");
        Cart cart = super.lambdaQuery()
                .eq(Cart::getUserId, userId)
                .eq(Cart::getStoreId, product.getStoreId())
                .eq(Cart::getProductId, productId)
                .one();
        if (ObjectUtil.isNull(cart)) {
            cart = new Cart();
            cart.setUserId(userId);
            cart.setStoreId(product.getStoreId());
            cart.setProductId(productId);
            cart.setBuyNum(buyNum);
            super.save(cart);
            return cart;
        } else {
            return this.modify(userId, productId, buyNum + cart.getBuyNum());
        }
    }

    /**
     * @Description
     * 删除购物车
     * @date 2025/1/13 11:01
     * @author FanJq
     * @param userId
     * @param ids
     * @return
    */
    @Override
    public void delete(String userId, String ids) {
        List<String> idList = Arrays.asList(ids.split(StringPool.COMMA));
        super.removeByIds(idList);
    }

    /**
     * @Description
     * 更新购物车
     * @date 2025/1/13 11:04
     * @author FanJq
     * @param userId
     * @param productId
     * @param buyNum
     * @return
    */
    @Override
    public Cart modify(String userId, String productId, Integer buyNum) {
        super.lambdaUpdate()
                .set(Cart::getBuyNum, buyNum)
                .eq(Cart::getUserId, userId)
                .eq(Cart::getProductId, productId)
                .update();
        Cart cart = new Cart();
        cart.setUserId(userId);
        cart.setProductId(productId);
        cart.setBuyNum(buyNum);
        return cart;
    }

    /**
     * @Description
     * 购物车信息
     * @date 2025/1/13 11:14
     * @author FanJq
     * @param userId
     * @param storeId
     * @return {@link List< CartResponse>}
    */
    @Override
    public List<CartResponse> getUserCartList(String userId, String storeId, String ids) {
        List<CartResponse> responseList = super.baseMapper.getUserCartList(userId, storeId, ids);
        return responseList;
    }

    /**
     * @Description
     * 购物车信息
     * @date 2025/1/13 16:03
     * @author FanJq
     * @param userId
     * @param storeId
     * @return {@link Map< String, Object>}
    */
    @Override
    public Map<String, Object> getCartInfo(String userId, String storeId) {
        List<CartResponse> cartList = this.getUserCartList(userId, storeId, null);
        List<DiscountRule> ruleList = discountRuleService.getByStoreId(storeId);
        String tip = "";
        if (CollectionUtil.isNotEmpty(ruleList)) {
            UserDiscountMark userStoreMark = discountMarkService.getUserStoreMark(userId, storeId);
            Integer index = 0;
            if (ObjectUtil.isNotNull(userStoreMark)) {
                index = userStoreMark.getNextMark() >= ruleList.size() ? 0 : userStoreMark.getNextMark();
            }
            DiscountRule rule = ruleList.get(index);
            tip = "再买" + rule.getMeet().stripTrailingZeros().toPlainString() +
                    "可享受减" + rule.getDiscountAmount().stripTrailingZeros().toPlainString() + "的优惠";
        }
        String finalTip = tip;
        return new HashMap<String, Object>(){{
            put("cartList", cartList);
            put("tip", finalTip);
        }};
    }
}
